/******************************************************************************
 * (c) 2011 Komersi Software                                                  *
 * www.komersisoftware.com                                                    *
 *                                                                            *
 * This file is part of Tadah                                                 *
 * Licensed under GNU General Public License v2.0                             *
 * Check LICENSE.TXT for more information                                     *
 ******************************************************************************/

#include <ctype.h>
#include <stdio.h>
#include <string.h>

#include "validation.h"
#include "definitions.h"

static int validate_token(const char *name, int length)
{
    int i;
    size_t len;

    // Length must be bigger than 1 character
    // and cannot be bigger than length
    len = strlen(name);
    if (len < 1 || len > length)
    {
        return FALSE;
    }

    // First character must be a letter
    if (!isalpha(name[0]))
    {
        return FALSE;
    }

    // Remaining characters may be letters, numbers or underline
    for (i = 1; i < len; i++)
    {
        if (!isalnum(name[i]) && name[i] != '_')
        {
            return FALSE;
        }
    }

    return TRUE;
}

#ifndef _MSC_VER
inline
#endif
int is_column_name_valid(const char *name)
{
	return validate_token(name, COLUMN_NAME_LENGTH);;
}

#ifndef _MSC_VER
inline
#endif
int is_table_name_valid(const char *name)
{
	return validate_token(name, TABLE_NAME_LENGTH);
}

#ifndef _MSC_VER
inline
#endif
char *generate_filename_table(const char *name)
{
    return generate_filename(name, TABLE_FILE_EXTENSION);
}

#ifndef _MSC_VER
inline
#endif
char *generate_filename_ddl(const char *name)
{
    return generate_filename(name, DDL_FILE_EXTENSION);
}

#ifndef _MSC_VER
inline
#endif
char *generate_filename_primary_index(const char *name)
{
    return generate_filename(name, PRIMARY_INDEX_FILE_EXTENSION);
}

char *uppercase_string(const char *string)
{
    char result[TABLE_NAME_LENGTH];
    int i;

    memset(result, 0, TABLE_NAME_LENGTH);
    strcpy(result, string);

    for (i = 0; i <= strlen(string); i++)
    {
        result[i] = toupper(result[i]);
    }

    return result;
}

char *generate_filename(const char *name, const char *extension)
{
    char filename[TABLE_NAME_LENGTH + 4 * sizeof(char)];

    strcpy(filename, uppercase_string(name));
    strcat(filename, extension);

    return filename;
}
